package cn.tedu.egmvc4.controller;

import cn.tedu.egmvc4.mapper.UserMapper;
import cn.tedu.egmvc4.pojo.dto.UserAddParam;
import cn.tedu.egmvc4.pojo.dto.UserUpdateParam;
import cn.tedu.egmvc4.pojo.entity.User;
import cn.tedu.egmvc4.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
@Slf4j
@Api(tags="用户管理系统")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("添加用户")
    @ApiOperationSupport(order=10)
    @PostMapping("add")
    public String addUsers(@RequestBody @Validated UserAddParam userAddParam){
        log.debug("userAddParam:"+userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam,user);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        return "添加用户成功";
    }

    @ApiOperation("查询用户")
    @ApiOperationSupport(order=20)
    @GetMapping("list")
    public List<UserListVO> listUsers(){
        log.debug("listUsers");
        List<UserListVO> list = userMapper.selectUsers();
        return list;
    }



    @ApiOperation("删除用户")
    @ApiOperationSupport(order=30)
    @ApiImplicitParam(name="id",value="用户ID",required=true,dataType="int")
    @PostMapping("del")

    public String delUsers(@Range(min=1,max=100,message="用户ID必须在1-100之间") @RequestParam Integer id){
        if (id<0){
            throw new IllegalArgumentException("用户ID不能小于0");
        }
        log.debug("id:"+id);
        userMapper.delUser(id);
        return "删除成功";
    }


    @ApiOperation("更新用户")
    @ApiOperationSupport(order=40)
    @PostMapping("update")
    public String updateUsers(UserUpdateParam userUpdateParam){
        log.debug("userUpdateParam:"+userUpdateParam);
        userMapper.updateUser(userUpdateParam);
        return "修改成功";
    }


}
